<template>
	<cl-popup v-model="visible" direction="bottom" size="auto" @close="handleClose">
		<view class="spec-selector">
			<!-- 商品信息头部 -->
			<view class="goods-header">
				<image :src="getImageSrc(goods.mainPic)" class="goods-image" mode="aspectFit" />
				<view class="goods-info">
					<view class="goods-name">{{ goods.title }}</view>
					<view class="goods-price" v-if="userStore.token">
						<text class="price-value">{{
							formatUserPrice(goods.price, userStore, goods.noDiscounts)
						}}</text>
						<text class="price-unit">/ {{ goods.unit }}</text>
						<text class="original-price" v-if="hasDiscount">
							{{ formatUserPrice(goods.price, userStore, 1) }}
						</text>
					</view>
					<view class="goods-price" v-else>
						<text class="price-login-tip">登录后查看价格</text>
					</view>
					<view class="goods-stock">
						库存：<text :class="stockStatusClass">{{ stockStatus }}</text>
					</view>
				</view>
				<view class="close-btn" @tap="handleClose">
					<cl-icon name="close" size="20" color="#999" />
				</view>
			</view>

			<!-- 商品规格信息 -->
			<view class="spec-section" v-if="goods.goodsSpec">
				<view class="section-title">规格</view>
				<view class="spec-info">
					<text class="spec-text">{{ goods.goodsSpec }}</text>
				</view>
			</view>

			<!-- 包装规格选择 -->
			<view class="package-section" v-if="goods.midpack > 1">
				<view class="section-title">包装规格</view>
				<view class="package-options">
					<view
						class="package-option"
						:class="{
							active: selectedPackage === 'single',
							disabled: goods.isMidpackSaleDisabled === 1,
						}"
						@tap="selectPackage('single')"
						v-if="goods.isMidpackSaleDisabled === 0"
					>
						<view class="option-name">单包装</view>
						<view class="option-desc">1{{ goods.unit }}</view>
					</view>
					<view
						class="package-option"
						:class="{ active: selectedPackage === 'midpack' }"
						@tap="selectPackage('midpack')"
					>
						<view class="option-name">中包装</view>
						<view class="option-desc">{{ goods.midpack }}{{ goods.unit }}</view>
					</view>
				</view>
			</view>

			<!-- 数量选择 -->
			<view class="quantity-section">
				<view class="section-title">数量</view>
				<view class="quantity-selector">
					<cl-input-number
						v-model="quantity"
						:min="1"
						:max="maxQuantity"
						:step="selectedPackage === 'midpack' && goods.midpack > 1 ? 1 : 1"
						size="large"
					/>
					<text class="quantity-unit">{{ currentUnit }}</text>
				</view>
				<view
					class="quantity-hint"
					v-if="selectedPackage === 'midpack' && goods.midpack > 1"
				>
					<text class="hint-text"
						>当前选择数量：{{ quantity * goods.midpack }}{{ goods.unit }}</text
					>
				</view>
			</view>

			<!-- 底部操作按钮 -->
			<view class="action-buttons">
				<button
					class="confirm-btn"
					:class="{ disabled: !canConfirm }"
					@tap="handleConfirm"
					:disabled="!canConfirm"
				>
					{{ mode === "cart" ? "加入购物车" : "立即购买" }}
				</button>
			</view>
		</view>
	</cl-popup>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import { formatUserPrice } from "/@/utils/price";
import { useStore } from "/@/cool/store";

interface Props {
	show: boolean;
	goods: any;
	mode: "cart" | "buy";
}

interface Emits {
	(e: "close"): void;
	(e: "confirm", spec: { count: number; packageType: string }): void;
}

const props = withDefaults(defineProps<Props>(), {
	show: false,
	goods: () => ({}),
	mode: "cart",
});

const emit = defineEmits<Emits>();
const { user: userStore } = useStore();

const visible = ref(false);
const quantity = ref(1);
const selectedPackage = ref("single");

// 计算属性
const maxQuantity = computed(() => {
	const stock = Number(props.goods.storNum || 0);
	if (selectedPackage.value === "midpack" && props.goods.midpack > 1) {
		return Math.floor(stock / props.goods.midpack);
	}
	return stock;
});

const currentUnit = computed(() => {
	if (selectedPackage.value === "midpack" && props.goods.midpack > 1) {
		return `${props.goods.midpack}${props.goods.unit}装`;
	}
	return props.goods.unit || "件";
});

const canConfirm = computed(() => {
	return quantity.value > 0 && quantity.value <= maxQuantity.value;
});

// 库存状态计算属性
const stockStatus = computed(() => {
	const stock = Number(props.goods.storNum || 0);
	return stock >= 100 ? "充足" : "紧张";
});

const stockStatusClass = computed(() => {
	const stock = Number(props.goods.storNum || 0);
	return stock >= 100 ? "text-green-500" : "text-orange-500";
});

const hasDiscount = computed(() => {
	// 检查用户是否有折扣
	return (
		userStore.token &&
		userStore.info?.discount &&
		userStore.info.discount < 1 &&
		props.goods.noDiscounts !== 1
	);
});

// 监听数量变化，自动调整到合法值
watch(quantity, (newVal) => {
	if (selectedPackage.value === "midpack" && props.goods.midpack > 1) {
		// 如果是中包装，调整到最近的合法值
		const maxAllowed = maxQuantity.value;

		// 如果输入值超过最大允许值，设置为最大允许值
		if (newVal > maxAllowed) {
			quantity.value = maxAllowed;
			return;
		}

		// 调整到最近的中包装倍数
		const remainder = newVal % 1;
		if (remainder !== 0) {
			// 如果有小数，向下取整
			quantity.value = Math.floor(newVal);
		}
	} else {
		// 单包装模式，只需要确保不超过库存
		if (newVal > maxQuantity.value) {
			quantity.value = maxQuantity.value;
		}
	}
});

// 监听show属性变化
watch(
	() => props.show,
	(newVal) => {
		visible.value = newVal;
		if (newVal) {
			// 重置数据
			quantity.value = 1;
			selectedPackage.value = "single";
		}
	}
);

// 监听visible变化
watch(visible, (newVal) => {
	if (!newVal) {
		emit("close");
	}
});

// 方法

function selectPackage(type: string) {
	if (type === "single" && props.goods.isMidpackSaleDisabled === 1) {
		return;
	}
	selectedPackage.value = type;
	quantity.value = 1; // 重置数量
}

function handleClose() {
	visible.value = false;
}

async function handleConfirm() {
	if (!canConfirm.value) {
		uni.showToast({ title: "请选择正确的数量", icon: "none" });
		return;
	}

	const actualCount =
		selectedPackage.value === "midpack" && props.goods.midpack > 1
			? quantity.value * props.goods.midpack
			: quantity.value;

	// 显示确认对话框
	const confirmText =
		selectedPackage.value === "midpack"
			? `确认加入${quantity.value}个${props.goods.midpack}${props.goods.unit}装（共${actualCount}${props.goods.unit}）到购物车？`
			: `确认加入${quantity.value}${props.goods.unit}到购物车？`;

	try {
		await uni.showModal({
			title: "确认",
			content: confirmText,
			confirmText: "确认",
			cancelText: "取消",
		});

		emit("confirm", {
			count: actualCount,
			packageType: selectedPackage.value,
		});
	} catch {
		// 用户取消操作
	}
}

// 获取图片源
function getImageSrc(src: string | null | undefined): string {
	if (!src) return "/static/empty/no.jpg";
	if (src.startsWith("http")) return src;
	if (src.startsWith("/")) return "https://shop.sdamdyy.cn" + src;
	return "https://shop.sdamdyy.cn/" + src;
}
</script>

<style lang="scss" scoped>
.spec-selector {
	padding: 0 32rpx 32rpx;
	min-height: 600rpx;
	max-height: 80vh;
	display: flex;
	flex-direction: column;
}

.goods-header {
	display: flex;
	align-items: center;
	padding: 32rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;
}

.goods-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
	background-color: #f5f5f5;
}

.goods-info {
	flex: 1;
	margin-left: 24rpx;
}

.goods-name {
	font-size: 28rpx;
	color: #333;
	line-height: 1.4;
	margin-bottom: 12rpx;
}

.goods-price {
	display: flex;
	align-items: baseline;
	margin-bottom: 8rpx;
}

.price-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #ff4757;
	margin-right: 8rpx;
}

.price-unit {
	font-size: 24rpx;
	color: #999;
	margin-right: 16rpx;
}

.original-price {
	font-size: 24rpx;
	color: #999;
	text-decoration: line-through;
}

.price-login-tip {
	font-size: 26rpx;
	color: #ff6b6b;
}

.goods-stock {
	font-size: 24rpx;
	color: #666;
}

.close-btn {
	position: absolute;
	top: 32rpx;
	right: 0;
	padding: 8rpx;
}

.spec-section,
.package-section,
.quantity-section {
	margin-top: 40rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
}

.spec-info {
	padding: 24rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
}

.spec-text {
	font-size: 26rpx;
	color: #666;
}

.package-options {
	display: flex;
	gap: 24rpx;
}

.package-option {
	flex: 1;
	padding: 24rpx;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	text-align: center;
	transition: all 0.3s ease;

	&.active {
		border-color: #667eea;
		background-color: #f8f9ff;
	}

	&.disabled {
		opacity: 0.5;
		pointer-events: none;
	}
}

.option-name {
	font-size: 26rpx;
	color: #333;
	margin-bottom: 8rpx;
}

.option-desc {
	font-size: 24rpx;
	color: #666;
}

.quantity-selector {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.quantity-unit {
	font-size: 26rpx;
	color: #666;
}

.prescription-notice {
	display: flex;
	align-items: center;
	gap: 12rpx;
	margin-top: 32rpx;
	padding: 24rpx;
	background-color: #fff7e6;
	border-radius: 12rpx;
}

.notice-text {
	font-size: 24rpx;
	color: #ff9500;
	line-height: 1.4;
}

.action-buttons {
	margin-top: 48rpx;
	padding-top: 32rpx;
	padding-bottom: env(safe-area-inset-bottom);
	border-top: 1rpx solid #f0f0f0;
}

.confirm-btn {
	width: 100%;
	height: 88rpx;
	font-size: 32rpx;
	font-weight: 600;
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: #ffffff;
	border: none;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;

	&:active:not(.disabled) {
		transform: scale(0.98);
		opacity: 0.9;
	}

	&.disabled {
		background: #cccccc;
		color: #ffffff;
		opacity: 0.6;
	}

	&::after {
		border: none;
	}
}

.quantity-hint {
	margin-top: 16rpx;
	padding: 12rpx 24rpx;
	background-color: #f8f9fa;
	border-radius: 8rpx;
}

.hint-text {
	font-size: 24rpx;
	color: #666;
}
</style>
